package com.ruoyi.project.pay;

import com.ruoyi.project.channel.businessInfo.domain.BusinessInfo;
import com.ruoyi.project.channel.businessInfo.mapper.BusinessInfoMapper;
import com.ruoyi.project.system.user.domain.User;
import com.ruoyi.project.system.user.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;

@Service
public class InvitationCodeGenerator {
    private static final int CODE_LENGTH = 6;
    private static final String CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    private static final Random RANDOM = new Random();
    private static final Set<String> generatedCodes = new HashSet<>();

    @Autowired
    private BusinessInfoMapper businessInfoMapper;
    @Autowired
    private UserMapper userRepository;

    @PostConstruct
    public void init() {
        // Load all existing invitation codes from the database
        businessInfoMapper.selectBusinessInfoList(new BusinessInfo()).forEach(user -> generatedCodes.add(user.getInvitationCode()));
        userRepository.selectUserList(new User()).forEach(user -> generatedCodes.add(user.getRemark()));
    }

    public String generateUniqueCode() {
        String code;
        do {
            code = generateCode();
        } while (generatedCodes.contains(code));
        generatedCodes.add(code);
        return code;
    }

    private String generateCode() {
        StringBuilder code = new StringBuilder(CODE_LENGTH);
        for (int i = 0; i < CODE_LENGTH; i++) {
            int index = RANDOM.nextInt(CHARACTERS.length());
            code.append(CHARACTERS.charAt(index));
        }
        return code.toString();
    }
}